package com.libraryManage.service.impl;

import com.libraryManage.commons.utils.MVCUtil;
import com.libraryManage.commons.utils.PageUtil;
import com.libraryManage.commons.utils.ResponseEntity;
import com.libraryManage.mapper.BookManageDoMapper;
import com.libraryManage.service.BookManageService;
import com.libraryManage.vo.BookManageVo;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @CreateDate 2021-01-26
 * @Author yufang
 */
@Service
public class BookManageServiceImpl implements BookManageService {

    @Autowired
    private BookManageDoMapper bookManageDoMapper;

    /**
     * 获取所有图书接口
     * @param vo
     * @return
     */
    @Override
    public ResponseEntity<List<BookManageVo>> getList(BookManageVo vo) {

        PageUtil.startPage(vo);
        List<BookManageVo> list = bookManageDoMapper.getList(vo);
        //统计图书的总数  图书总数 = 借出图书数 + 图书库存数
        list.forEach(bookManageVo -> {
            //判断图书是否被借出,如果没被借出则 图书总数 = 图书库存数
            if(bookManageVo.getBorrowNum() > 0){
                bookManageVo.setBookNum(bookManageVo.getStockNum() + bookManageVo.getBorrowNum());
            }else {
                bookManageVo.setBookNum(bookManageVo.getStockNum());
            }
        });
        return PageUtil.tranferPage(list);

    }

    /**
     * 图书上架or下架
     * @param bookId
     * @param bookState
     * @return
     */
    @Override
    public ResponseEntity<List<BookManageVo>> updateBookState(int bookId, int bookState) {
        //1.先更改图书的状态
        bookManageDoMapper.updateBookState(bookId,bookState);
        //2.查询图书（相当于更新用户界面）
        BookManageVo vo = new BookManageVo();
        bookState = bookState == 0 ? 1 : 0;
        vo.setBookState(bookState);
        //配置分页属性
        vo.setPageNum(1);
        vo.setPageSize(10);
        return getList(vo);
    }

    /**
     * 更新图书基本信息
     * @param vo
     * @return
     */
    @Override
    public ResponseEntity<List<BookManageVo>> updateBookData(BookManageVo vo) {
        //1.更新图书信息
        bookManageDoMapper.updateBookData(vo);
        // 2.查询所有图书（更新页面内容）
        BookManageVo bookManageVo = new BookManageVo();
        bookManageVo.setBookState(vo.getBookState());
        //配置分页属性
        bookManageVo.setPageNum(1);
        bookManageVo.setPageSize(10);
        return getList(bookManageVo);
    }

    /**
     * 获取热门图书
     * @return
     */
    @Override
    public ResponseEntity<List<BookManageVo>> getHotBook() {

        List<BookManageVo> list = bookManageDoMapper.getHotBook();
        return MVCUtil.response(list);

    }

    /**
     * 更新热门书籍
     * @param hotState
     * @param bookId
     * @return
     */
    @Override
    public ResponseEntity<List<BookManageVo>> updateHotBook(int hotState, int bookId) {

        bookManageDoMapper.updateHotBook(hotState,bookId);
        return getHotBook();

    }

}
